﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DPS.Prototype.Model;


namespace DPS.Prototype.PolicyBase.Filters.WorkOrderFilters
{
    public class GIDateFilters : WorkOrderFiltersBase
    {
        protected override List<Model.WorkOrder> FilterProcess(List<Model.WorkOrder> matchedOrders, ProdCompetitorBase prodCompetitor)
        {
            List<WorkOrder> retOrders = new List<WorkOrder>();
            foreach (WorkOrder wo in matchedOrders)
            {
                if (CheckCapacityBeforeGIDate(prodCompetitor, wo))
                {
                    retOrders.Add(wo);
                }
            }
            return retOrders;
        }

        /// <summary>
        /// Check available capacity before GIDate
        /// </summary>
        /// <param name="prodCompetitor"></param>
        /// <param name="order"></param>
        /// <returns></returns>
        private bool CheckCapacityBeforeGIDate(ProdCompetitorBase prodCompetitor, WorkOrder order)
        {
            DateTime GIDate = order.GIDate;
            Capacity currentCapacity = prodCompetitor.LastProducedCapacity;
            if (currentCapacity == null)
            {
                currentCapacity = prodCompetitor.ProdLine.Capacitys.First();
            }
            DateTime endTime = GIDate.AddHours(-SystemSettings.WorkOrderLeadTimeHours);
            float avilableCapacity = prodCompetitor.ProdLine.Capacitys.Where(c => c.StartTime >= currentCapacity.StartTime && c.StartTime <= endTime).Sum(c => (c.TotalUsage - c.OccupiedUsage));
            return avilableCapacity >= order.OpenOrderQty;
        }
    }
}
